import {ChatModel} from "../../../models/chat";
import {config} from "../../../config";
const util = require('../../../utils/util.js');

const chatModel = new ChatModel()
const app = getApp()
const recorderManager = wx.getRecorderManager()
const innerAudioContext = wx.createInnerAudioContext()//播放录音 返回值 innerAudioContext
Page({

  /**
   * 页面的初始数据
   */
  data: {
    InputBottom: 0,
    inputValue: '',
    userInfo:{},
    nickname:'',
    chatLog:[],
    user:{},
    chatId:'',
    showKey:true,
    isRecording:false,
    startPoint: {}, //记录长按录音开始点信息,用于后面计算滑动距离。
    sendLock: true, //发送锁，当为true时上锁，false时解锁发送
  },
  InputFocus:function(e) {
    this.setData({
      InputBottom: e.detail.height
    })
  },
  InputBlur:function(e) {
    this.setData({
      InputBottom: 0
    })
  },
  bindKeyInput: function (e) {
    this.setData({
      inputValue: e.detail.value
    })
  },
  handlerClickAudio(event) {
    this.setData({
      showKey:!this.data.showKey
    })
  },
  handlerSubmit: function (event) {
    chatModel.sendTextMessage(this.data.chatId, this.data.inputValue,).then(res=>{
      this._addMessage(this.data.inputValue,null,0)
      this.bottom()
    })
  },
  _addMessage(content,duration,type) {
    const chatLog = this.data.chatLog
    const log = {
      avatarUrl: this.data.user.avatarUrl,
      chatId: this.data.chatId,
      content: content,
      duration:duration,
      createTime: util.formatTime(new Date()),
      type: type,
      userId:this.data.user.userId
    }
    chatLog.push(log)
    this.setData({
      chatLog
    })
    this.bottom()
  },
  handlerClickPhoto(event) {
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], //从相册选择
      success: (res) => {
        wx.showLoading({
          title: '发送中...',
        })
        this.uploadImage(res.tempFilePaths[0])
      }
    });
  },

  uploadImage(path) {
    let _this = this
    wx.uploadFile({
      url: config.api_blink_url+'/v/chat/sendImageMessage',
      filePath: path,
      header:{
        'token': wx.getStorageSync('token')
      },
      formData:{
        chatId:this.data.chatId,
      },
      name: 'file',
      success (res){
        console.log(res.data)
        wx.hideLoading()
        if (res.statusCode ==200) {
          _this._addMessage(path,null,2)
        }
      }
    })
  },
  //开始录音的时候
  start: function() {
    let _this = this
    const options = {
      duration: 60000, //指定录音的时长，单位 ms
      sampleRate: 16000, //采样率
      numberOfChannels: 1, //录音通道数
      encodeBitRate: 96000, //编码码率
      format: 'mp3', //音频格式，有效值 aac/mp3
      frameSize: 50, //指定帧大小，单位 KB
    }
    //开始录音
    recorderManager.start(options);
    recorderManager.onStart(() => {
      console.log('录音中...')
      _this.setData({
        isRecording: true,
        sendLock: false //长按时是不上锁的。
      })
    });
    //错误回调
    recorderManager.onError((res) => {
      console.log(res, "aaas");
    })
  },

  //停止录音
  stop: function() {
    recorderManager.stop()
    this.setData({
      isRecording: false
    })
    recorderManager.onStop((res) => {
      //如果是锁住状态
      if (this.data.sendLock) {
        return
      }
      console.log('开始发送。。')
      if (res.duration < 1000) {
        app.showInfo('录音时间太短！')
        return
      } else {
        wx.showLoading({
          title: '发送中...',
        })
        console.log(res.tempFilePath)
        const duration = (res.duration/1000).toFixed()
        // 上传 录音文件
        wx.uploadFile({
          header:{
            'token': wx.getStorageSync('token')
          },
          url: config.api_blink_url+'/v/chat/sendAudioMessage',
          filePath: res.tempFilePath,
          formData:{
            chatId:this.data.chatId,
            duration:duration
          },
          name: 'file',
          success: (res) => {
            let object = JSON.parse(res.data);
            this._addMessage(object.data,duration,1)
            wx.hideLoading()
            console.log('停止录音', object.data)
          },
        })
      }
    });
  },

  //播放声音
  handlerPlay: function(event) {
    console.log('play....')
    const index = event.target.dataset.id
    const data = this.data.chatLog[index]
    if (data.type != 1) {
      return
    }
    console.log(data)
    //音频地址
    innerAudioContext.src = data.content;

    //在ios下静音时播放没有声音，默认为true，改为false就好了。
    innerAudioContext.obeyMuteSwitch = false;

    //点击播放
    innerAudioContext.play();
    // //播放结束
    innerAudioContext.onEnded(() => {
      innerAudioContext.stop();
    });
  },

  longTap: function() {
    console.log('longTap....')
  },

  touchStart: function(e) {
    console.log('touchStart....')
    this.start();
    this.setData({
      startPoint: e.touches[0],//记录触摸点的坐标信息
    })
  },
  touchEnd: function() {
    console.log('touchEnd....')
    this.stop()
  },
  handleTouchMove:function(e) {
    let isRecording = true
    let sendLock = false
    //touchmove时触发
    let moveLength = e.touches[e.touches.length - 1].clientY - this.data.startPoint.clientY; //移动距离
    if (Math.abs(moveLength) > 50) {
      wx.showToast({
        title: "松开手指,取消发送",
        icon: "none",
      });
      sendLock = true;//触发了上滑取消发送，上锁
      isRecording = false
    }
    this.setData({
      isRecording: isRecording,
      sendLock: sendLock
    })
  },
  _Load(id) {
    wx.showLoading({
      title: '正在加载中...',
    })
    chatModel.getDetail(id).then(res=>{
      this.setData({
        chatLog:res.data.chatLog,
        chatId:res.data.chatId,
        user:res.data.user
      })
      wx.hideLoading()
      this.bottom()
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    app.checkLoginStatus()
    let id = options.userId
    this.setData({
      nickname:options.nickname
    })
    // this._Load(id)
    this._Load(19)
    let isIphoneX = app.globalData.isIphoneX;
    this.setData({
      isIphoneX: isIphoneX
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    let nickname = this.data.nickname
    // 页面首次渲染完毕时执行
    if (typeof (nickname) != 'undefined' && nickname!='') {
      wx.setNavigationBarTitle({
        title: nickname
      });
    }
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  bottom: function () {
    // 使页面滚动到底部
    wx.pageScrollTo({
      scrollTop: 1000000
    })
  }
})
